package WorkTask3;


import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// a. 使用线程池将一个目录中的所有内容拷贝到另外一个目录中，包含子目录中的内容。
//    b.实现将指定目录中的所有内容删除，包含子目录中的内容都要全部删除。
public class ThreadPoolTask implements Runnable {
   static File file1 = new File("D:\\目录1");
   static File file2 = new File("D:\\复制的目录");
    public static void main(String[] args) {
        ThreadPoolTask tpt = new ThreadPoolTask();
        /*ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(tpt);
        executorService.shutdown();*/
        delete(file2);

        /* show(file1);*/
        //delete(file2);

    }


    public static void show(File exist,File copyFile){
        if (!exist.exists()){
            exist.mkdirs();
        }
        if (!copyFile.exists()){
            copyFile.mkdirs();
        }
        File[] files = exist.listFiles();
        for (File f : files) {
            if (f.isFile()){
                copy(new File(exist + "\\" + f.getName()),new File(copyFile + "\\" + f.getName()));
            }else {
                show(new File(exist + "\\" + f.getName()),new File(copyFile + "\\" + f.getName()));
            }
        }
    }

    public static void copy(File exist,File copyFile){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(exist));
            bos = new BufferedOutputStream(new FileOutputStream(copyFile));
            int res = 0;
            byte[] b = new byte[1024];
            while ((res = bis.read(b)) != -1){
                bos.write(b,0,res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {if (null != bos){
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != bis){
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void delete(File file){
        File[] files = file.listFiles();
        for (File f : files){
            if (f.isFile()){
                f.delete();
            }else {
                delete(f);
                f.delete();
            }
        }

    }


    @Override
    public void run() {
        show(file1,file2);
    }
}
